package ppa.marc.importer;

import java.io.File;
import java.io.PrintStream;
import java.util.List;

import ppa.marc.domain.Record;
import ppa.marc.importer.reader.RecordsReader;
import ppa.marc.importer.writer.RecordsInserter;

public class TransactionalImportController implements ImportController {
	private final PrintStream errorStream;
	private final ArgumentParser argumentParser;
	private final RecordsReader recordsReader;
	private final RecordsInserter recordsInserter;

	public TransactionalImportController(ArgumentParser argumentParser, RecordsReader recordsReader, RecordsInserter recordsInserter, PrintStream errorStream) {
		this.argumentParser = argumentParser;
		this.recordsReader = recordsReader;
		this.recordsInserter = recordsInserter;
		this.errorStream = errorStream;
	}

	public void importRecords(String[] arguments) {
		try {
			argumentParser.parseArguments(arguments);
			File sourceFile = argumentParser.getSourceFile();
			insertRecords(sourceFile, recordsReader.readRecords(sourceFile));
		}
		catch(IllegalArgumentException illegalCommandLineArguments) {
			errorStream.println("Import failed: " + illegalCommandLineArguments.getMessage());
		}
		catch(RuntimeException dataInsertionFailure) {
			errorStream.println(dataInsertionFailure.getMessage());
		}
	}

	private void insertRecords(File sourceFile, List<Record> records) {
		if(records.isEmpty()) {
			errorStream.println("Records weren't found from file " + sourceFile.getName() + ".");
		}
		else {
			recordsInserter.insertRecords(records);
		}
	}
}
